const Koa = require('koa');
const Router = require('koa-router');
const cheerio = require('cheerio');
const http = require('http');
const cors = require('koa2-cors');
const bodyParser = require('koa-bodyparser');
const passport = require('koa-passport');
const session = require('koa-session')
const sessionConfig = require('./config/sessionConfig')
const mongoose = require('mongoose');
const users = require('./routes/api/users');
const siteCollect = require('./routes/api/siteCollect')
const mongoUrl = require('./config/keys');
const serve = require('koa-static')
const path = require('path')

mongoose.connect(mongoUrl.mongoURL, { useNewUrlParser: true }).then(()=>{
    console.log('mongodb连接成功')
});
const staticFile = serve(path.join(__dirname),'./static');
const app = new Koa();
const router = new Router();
app.use(staticFile)
app.keys = ['some secret hurr'];
app.use(session(sessionConfig,app));
app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/test') {
            return "*"; // 允许来自所有域名请求
        }
        // return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了

        return 'http://localhost:8080';
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
app.use(bodyParser());


app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);

router.get('/',(ctx,next)=>{
    ctx.body = '根路径服务器已联通'
    console.log('根路径服务器已联通')
    next()

})


app.use(async (ctx,next)=>{
    console.log('session信息',ctx.session.user)
    await next()
})
router.get('/weather',async (ctx,next)=>{

    let htmlTxt = await new Promise((resolve)=>{
        http.get('http://www.nmc.cn/publish/forecast/china.html',function(res){

            res.setEncoding('utf8');
            let rawData = '';
            res.on('data', (chunk) => { rawData += chunk; });
            res.on('end', () => {
              try {
                const parsedData = JSON.parse(rawData);
                console.log(parsedData);
              } catch (e) {
                // console.error(e.message);
              }
              resolve(rawData);
            });
        })
    });
    let $ = cheerio.load(htmlTxt);
    let allWeather = [];
    let result = $('.right-container .content').children('.area').find('li').map(function(index,el){
        let city = $('.cname a',$(el)).text();
        let weather = $('.weather',$(el)).text();
        let temp = $('.temp',$(el)).text();
        // console.log({city,weather,temp});
        allWeather.push({city,weather,temp}) 
    });
    ctx.body = JSON.stringify(allWeather);
    console.log('weather已联通')
})


router.use('/api/users',users);
router.use('/api',siteCollect);

app.use(async (ctx,next)=>{
    console.log('原生路由响应',ctx.path)
    if(ctx.path === '/') {
        ctx.body = "后一个"
    }
    await next()
})
app .use(router.routes())
    .use(router.allowedMethods());


// app.listen(3000);
const server = app.listen(3000);
server.setTimeout(0)